import Vue from 'vue'
import VueRouter from 'vue-router'
import Outer from '../views/Outer.vue'
import Login from '../views/Login.vue'
import Tree from '../components/Tree.vue'
import Config from '../components/Config.vue'
import Test from '../components/Test.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/user',
    name: 'outer',
    component: Outer,
    show: false,
    meta: {
      need2Login: true,
      title: '简道云解决方案实验室'
    },
    children: [
      {
        path: 'tree',
        component: Tree,
        meta: {
            need2Login: true,
          title: '解决方案实验室'
        },
      },
      {
        path: 'config',
        component: Config,
        meta: {
            need2Login: true,
          title: '简道云解决方案实验室'
        },
      },
      {
        path: 'test',
        component: Test,
        meta: {
          need2Login: true,
          title: '简道云解决方案实验室'
        },
      },
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录JDY-SOLUTION'
    },
  },
  {
      path: '*',
      redirect: '/user',
  }
]




const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => { //全局钩子函数，路由守卫拦截
  to.matched.some((route) => {
    var login_state = JSON.parse(localStorage.getItem("login_state"));
    if (route.meta.need2Login) { // 识别需要登录验证页面
      if (login_state === 1) { // 判断登录状态-通过
        next();
        //console.log("pass")
      } else { // 否则跳转登录页面
        next({ name: 'Login', params: { path: "/login" } });
        //console.log("login")
      }
    } else { // 不需要登录的页面放行
      next();
      //console.log("noneed")
    }
  });
});

const originalPush = VueRouter.prototype.push // 为解决router大于3.0版本的问题，而设立的解决代码
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

export default router
